# views.py

import pdb, itertools
import psd.register.demographics

from django.shortcuts import render_to_response
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.models import User
from django.template import RequestContext

from django.http import Http404, HttpResponseRedirect, HttpResponseNotFound

from psd.register.models import Person, RegRecord, BreakRecord, DateRecord, CruiseRecord, Event, MatchRecord, TableRecord, fetch_regrecord
from psd.register.matchmaker import updateMatchRecords_async
from psd.register.views.printouts import make_schedules
from psd.RcodeHooks import print_demographics, print_demographics_async, schedule_async
from django.core.urlresolvers import reverse
from psd.register.forms import ScheduleForm, NextSheetForm
from django.forms.models import modelformset_factory
from django.forms.formsets import formset_factory
from psd.register.forms import BreakForm, MultiBreakForm, CruiseForm

import psd.register.views.contact

import sys
from django.http import HttpResponse


def HttpStreamTextResponse( rprocess, event_name, headers=True, head_string="", ACTIONS=None ):
    """ 
    Wrap the output from the asyncronous R commands with some html so it renders pretty
    We use the 'yield' generator so we can have django render the html to the screen as it
    is generated, so the user does not worry about it never showing up.
    """
    
    head = ( "<h1>Streaming Function Call Wrangler</h1>\noutput should appear on screen as it is generated<hr>",
             head_string,
             "<pre>", )
    act_menu = render_to_response( 'event_manager_actions.txt', {'event_name':event_name, 'actions':ACTIONS} )
    tail = ( "</pre><hr>\n", act_menu.content, "\n<hr>\n" )

    if rprocess != None:
        if headers:
            return HttpResponse( itertools.chain( head, rprocess, tail ) )
        else:
            return HttpResponse( rprocess )
    else:
        return HttpResponse( itertools.chain( head, ["Failure to launch/call process.\n", "Sorry"], tail ) )



def print_http_response(f):
    """ 
    A Decorator 
    Wraps a python function that prints to the console, and 
    returns those results as a HttpResponse (HTML)
    """
    
    class WritableObject:
        def __init__(self):
            self.content = []
        def write(self, string):
            self.content.append(string)     
    
    def new_f(*args, **kwargs):
        printed = WritableObject()
        sys.stdout = printed
        f(*args, **kwargs)
        sys.stdout = sys.__stdout__    
        return HttpResponse(['<br>' if c == '\n' else c for c in printed.content ])         
    return new_f







@print_http_response  
def test_function_http_resp(request):  
       print "some output here"  
       for i in [1, 2, 3]:  
          print i  


import time
def playpipe():
    for i in range(30):
        yield "line %s\n" % (i, )
        time.sleep(1)
        

def test_function(request):  
       return HttpResponse( playpipe() )


